﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using Framework.Base;
using Framework.ECS;
using UnityEngine;

namespace Framework.Game
{
   public class BaseGameObject: BaseEntity
   {

      public string name = "";

      public BaseGameObject()
      {
         BaseGameObjectMgr.instance.AddGameObject(this);
      }
      
   }

   public class SingleGameObject<T> : BaseGameObject where T : BaseGameObject,new()
   {
      private static T m_sInstance = null;

      public static T instance
      {
         get{
            if (m_sInstance == null || !m_sInstance.IsVailed())
            {
               m_sInstance = new T();
            }

            return m_sInstance;
         }
      }

   }

   public class BaseGameObjectMgr
   {
      private static BaseGameObjectMgr m_sMgr = null;

      public static BaseGameObjectMgr instance
      {
         get
         {
            if(m_sMgr == null)
            {
               m_sMgr = new BaseGameObjectMgr();
            }

            return m_sMgr;
         }
      }
   
      private Dictionary<string, BaseGameObject> m_ObjectDict = new Dictionary<string, BaseGameObject>();
      public void AddGameObject(BaseGameObject gameObj)
      {
         
         AddGameObject(gameObj.name, gameObj);
      }

      public void AddGameObject(string name, BaseGameObject gameObj)
      {
         if (name == "")
         {
            name = gameObj.GetType().Name;
         }
         if (m_ObjectDict.ContainsKey(name))
         {
            Debug.Log("err" + name);
            //throw new Exception("err addd gameObject");
         }
         else
         {
            m_ObjectDict[name] = gameObj;
         }

      }

      public void RemoveGameObject(BaseGameObject gameObject)
      {
         if (gameObject.IsVailed())
         {
            var name = gameObject.name;
            m_ObjectDict.Remove(name);
            gameObject.Destroy();
         }
      }

      public void RemoveGameObject(string name)
      {
         if (m_ObjectDict.TryGetValue(name, out var removeObj))
         {
            RemoveGameObject(removeObj);
         }
      }

   }
}